<?php
/*
 *
 *
 * This software has been made FREELY available by author for interest of the developers. 
 *      I hope this will help you in coding faster and robust php application
 *            You can modify and use it as you it suits you.
 *              Your comments, suggestions and corrections 
 *                          will be highly 
 *                           APPRECIATED. 
 *                                      Thanks, 
 *                                      Author
 * @author :   Roshan Budhathoki (contact@roshanbudhathoki.com);
 * @URL    :   <http://www.roshanbudhathoki.com>
 *
 *
 */

class plugins {
	
	private static $hooks;
	private $plugins = array ();
	
	function __construct() {
		$this->getActivePlugins ();
		$this->hooks = array ();
	}
	
	public static function addHook($hook, $function, $priority = 5) {
		
		$found_plugin = false;
		if (isset ( $this->hooks [$hook] )) {
			if (is_array ( $this->hooks [$hook] )) {
				foreach ( $this->hooks [$hook] as $fxName ) {
					if ($fxName == $function) {
						$found_plugin = true;
						break;
					}
				}
			}
		}
		if (! $found_plugin) {
			$this->hooks [$hook] [$priority] [] = $function;
		}
	}
	
	public static function removeHook($hook, $function) {
		unset ( $this->hooks [$hook] [$function] );
	}
	
	public static function runHook($hook) {
		$args = func_get_args ();
		array_shift ( $args );
		if (isset ( $this->hooks [$hook] )) {
			for($priority = 0; $priority <= 10; $priority ++) {
				if (isset ( $this->hooks [$hook] [$priority] ) && is_array ( $this->hooks [$hook] [$priority] )) {
					foreach ( $this->hooks [$hook] [$priority] as $fxName ) {
						if (function_exists ( $fxName )) {
							call_user_func_array ( $fxName, $args );
						}
					}
				}
			}
		}
	}
	
	function run() {
		if (is_array ( $this->plugins )) {
			foreach ( $this->plugins as $key => $value ) {
				include PLUGIN_PATH . $value ['path'];
			}
		}
		$this->hooks = array ();
	}
	
	function reload() {
		$this->getActivePlugins ();
		$this->run ();
	}
	
	function getActivePlugins() {
		$this->plugins = unserialize ( preference::newInstance ()->getPreference ( 'active_plugins' ) );
	}
	function activate($plugin) {
		if (! is_array ( $plugin )) {
			throw new Exception ( 'Invalid plugin information supplied' );
		}
		
		if (! array_key_exists ( $plugin ['name'], $this->plugins )) {
			$this->plugins [$plugin ['name']] = $plugin;
		}
		preference::newInstance ()->setPreference ( 'active_plugins', "'" . serialize ( $this->plugins ) . "'" );
		$this->getActivePlugins ();
	}
	
	function deactivate($name) {
		if (array_key_exists ( $name, $this->plugins )) {
			unset ( $this->plugins [$name] );
		} else {
			throw new Exception ( 'Plugin does not exist.' );
		}
		preference::newInstance ()->setPreference ( 'active_plugins', "'" . serialize ( $this->plugins ) . "'" );
		$this->getActivePlugins ();
	}

}